<?php

class FormHelper {

    const HIGHLIGHT_CSSCLASS = 'ui-state-highlight';

    static $strReadonly='';

    public function setReadonly($b=true) {
        if ($b) {
            self::$strReadonly = 'readonly="readonly"';
        } else {
            self::$strReadonly = '';
        }
    }

    public static function filter($s){
        return str_replace('"','\"',$s);
    }
	public static function StartForm($name, $action) {
		echo '<form autocomplete="off" name="'.$name.'" action="'.$action.'" enctype="multipart/form-data" method="post">';
	}

	public static function EndForm() {
		echo '</form>';
	}
	
	public static function htmlConv($string , $quote_style=ENT_QUOTES , $charset='UTF-8' , $double_encode=false) {
		return htmlspecialchars ( $string , $quote_style , $charset , $double_encode );
	}

	public static function TextField($name, $value, $label='', $highlight=false, $css_class='ruler input_status', $mandatory=0, $singleline=false) {
        $value = self::htmlConv($value);
        $strReadonly = self::$strReadonly;
        $strHighlight = ($strReadonly !== '' & $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
        $strMandatory = '';
        if ($mandatory > 0) {
            $strMandatory = '<ins title="mandatory field">' . str_repeat('*', $mandatory) . '</ins>';
        }
        $input = $strReadonly === '' ? '<input id="'.$name.'" name="'.$name.'" type="text" class="text '.$css_class.'" value="'.$value.'" '.$strReadonly.' />' : '<p>'.$value.'</p>';
		if ($label === '') $label = $name;
		$strSingleline = $singleline ? 'form-item-1c':'';
        echo <<<HTML
        <div class="form-item $strSingleline $strHighlight">
            <span class="grid-l"><label for="$name">{$strMandatory}{$label} :</label></span>
            <span class="grid-r">
                $input
            </span>
        </div>
HTML;
	}

    //for multi-language (phase 2)
	public static function TextField2($name, $value, $label='', $highlight=false) {
	    $value = self::htmlConv($value);
		if ($label === '') $label = $name;
        echo <<< HTML
        <div class="form-item">
            <span class="grid-l"><label for="$name">{$label} :</label></span>
            <span class="grid-r">
                <input id="$name" name="$name" type="text" class="ruler input_status text" value="$value" />
                <img class="lang-icon-s" src="images/hkg.jpg" title="繁體中文" alt="繁體中文" />
            </span>
        </div>
HTML;
	}

	public static function FirstLastName($arr=array('first'=>array('name'=>'','value'=>''),'last'=>array('name'=>'','value'=>'')), $label='', $is_cn=false, $highlight=false, $css_class='ruler input_status') {
        $arr['first']['value'] = self::htmlConv($arr['first']['value']);
        $arr['last']['value'] = self::htmlConv($arr['last']['value']);
        $strReadonly = self::$strReadonly;
        $strHighlight = ($strReadonly !== '' && $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
        $strEn = $is_cn ? '' : 'en';
        if ($strReadonly === '') {
            $input = <<<HTML
            <span class="last">
                <span><ins class="en">Last</ins><ins class="cn">姓</ins></span>
                <input type="text" value="{$arr['last']['value']}" name="{$arr['last']['name']}" class="text {$css_class}" />
            </span>
            <span class="first">
                <span><ins class="en">First</ins><ins class="cn">名</ins></span>
                <input type="text" value="{$arr['first']['value']}" name="{$arr['first']['name']}" class="text {$css_class}" />
            </span>
HTML;
        } else {
            if ($is_cn) {
                $input = '<p>'.$arr['last']['value'].' '.$arr['first']['value'].'</p>';
            } else {
                $input = '<p>'.$arr['first']['value'].' '.$arr['last']['value'].'</p>';
            }
        }
        echo <<<HTML
        <div class="form-item name $strHighlight">
            <span class="grid-l"><label>{$label} :</label></span>
            <span class="grid-r {$strEn}">
                $input
            </span>
        </div>
HTML;
	}

	public static function TextArea($name, $value, $label='', $highlight=false, $mandatory=0) {
	    $value = self::htmlConv($value);
        $strReadonly = self::$strReadonly;
        $strHighlight = ($strReadonly !== '' & $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
        $strMandatory = '';
        if ($mandatory > 0) {
            $strMandatory = '<ins title="mandatory field">' . str_repeat('*', $mandatory) . '</ins>';
        }
		if ($label === '') $label = $name;
		if ($strReadonly !== '') {
            $value = nl2br($value);
        }else{
            $value = preg_replace("/\<br\ ?\/?\>/", "\r\n", $value);
        }
        $textarea = ($strReadonly === '') ? '<textarea id="'.$name.'" name="'.$name.'" class="resizeable">'.$value.'</textarea>' : '<p class="textarea">'.$value.'</p>';
        echo <<< HTML
        <div class="form-item form-item-1c $strHighlight">
            <span class="grid-l"><label for="$name">{$strMandatory}{$label} :</label></span>
            <span class="grid-r">
                $textarea
            </span>
        </div>
HTML;
	}

    //for multi-language (phase 2)
	public static function TextArea2($name, $value, $label='', $confirm=false, $url='', $highlight=false) {
	    $value = self::htmlConv($value);
		if ($label === '') $label = $name;
        $confirm_button = $confirm === true ? '<input type="hidden" value="'.$url.'" /><input type="button" value="add" class="btn ui-state-default ui-corner-all confirm" />' : '';
        echo <<< HTML
        <div class="form-item form-item-1c">
            <span class="grid-l"><label for="$name">$label :</label></span>
            <span class="grid-r">
                <textarea id="$name" name="$name" class="resizeable">$value</textarea>
                <img class="lang-icon-s" src="images/hkg.jpg" title="繁體中文" alt="繁體中文" />
                $confirm_button
            </span>
        </div>
HTML;
	}

	public static function ProtectedField($value, $label='', $isSingleLayout=false) {
	    $value = self::htmlConv($value);
        $str_class = $isSingleLayout ? 'form-item-1c' : '';
        echo <<< HTML
        <div class="form-item $str_class">
            <span class="grid-l">$label :</span>
            <span class="grid-r"><p>$value</p></span>
        </div>
HTML;
	}

	public static function HiddenField($name, $value) {
	    $value = self::htmlConv($value);
        echo <<< HTML
		    <input type="hidden" name="$name" value='$value' />
HTML;
	}

    public static function DropDownList($name='', $arr, $default='', $label='', $highlight=false, $mandatory=0) {
        $strReadonly = self::$strReadonly;
        $strHighlight = ($strReadonly !== '' & $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
        $strMandatory = '';
        if ($mandatory > 0) {
            $strMandatory = '<ins title="mandatory field">' . str_repeat('*', $mandatory) . '</ins>';
        }
        if ($strReadonly === '') {
            $atr_name = 'name="'.$name.'"';
            if ($label === '') $label = $name;
            if ($name === '') $atr_name = '';
            $option_list = '';
            foreach($arr as $k => $v){
                $option_list .= '<option value="'.self::htmlConv($k).'"'.($k==$default ? ' selected="selected"':'') . '>' . self::htmlConv($v) . '</option>' . "\n";
            }
            echo <<< HTML
            <div class="form-item">
                <span class="grid-l"><label for="$name">{$strMandatory}{$label} :</label></span>
                <span class="grid-r">
                <select $atr_name $strReadonly>
                $option_list
                </select>
                </span>
            </div>
HTML;
        } else {
            $value = $default === '' ? '' : $arr[$default];
            $value = self::htmlConv($value);
            echo <<< HTML
            <div class="form-item $strHighlight">
                <span class="grid-l"><label for="$name">$label :</label></span>
                <span class="grid-r">
                    <p>$value</p>
                </span>
            </div>
HTML;
        }

    }

	public static function RadioButton($name, $arr, $default='', $label='', $highlight=false, $mandatory=0) {
        $strReadonly = self::$strReadonly;
        $strHighlight = ($strReadonly !== '' & $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
        $strMandatory = '';
        if ($mandatory > 0) {
            $strMandatory = '<ins title="mandatory field">' . str_repeat('*', $mandatory) . '</ins>';
        }
        echo '<div class="form-item '.$strHighlight.'">';
        echo '<span class="grid-l"><label>'.$strMandatory.$label.' :</label></span>';
        echo '<span class="grid-r">';
        if ($strReadonly === '') {
            echo '<table><tr>';
            $i = 0;
            foreach($arr as $k => $v){
                if ($i%3===0 & $i!==0) echo '</tr><tr>'; 
                $str_checked = ( ($k==$default) ? 'checked="checked"' : '');
                echo '<td class="ui-widget-content"><label for="',$name,'-',$i,'">',self::htmlConv($arr[$k]),'<input type="radio" ',$str_checked,' value="',self::htmlConv($k),'" id="',$name,'-',$i,'" name="',$name,'" ',$strReadonly,' /></label></td>';
                $i++;
            }
            echo '</tr></table>';
        } else {
            $value = isset($arr[$default]) ? $arr[$default] : '';
            $value = self::htmlConv($value);
            echo '<input name="'.$name.'" type="text" value="'.$value.'" '.$strReadonly.' />';
        }
        echo '</span></div>';
	}

	public static function CheckBox($name, $arr, $label='', $highlight=false, $layout_1c=true, $mandatory=0) {
        $strReadonly = self::$strReadonly;
        $strHighlight = ($strReadonly !== '' & $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
        $length = count($arr);
        $strMandatory = '';
        if ($mandatory > 0) {
            $strMandatory = '<ins title="mandatory field">' . str_repeat('*', $mandatory) . '</ins>';
        }
        echo '<div class="form-item '.($layout_1c?'form-item-1c':'').' '.$strHighlight.'">';
        echo '<span class="grid-l"><label>'.$strMandatory.$label.' :</label></span>';
        echo '<span class="grid-r">';
        if ($strReadonly === '') {
            echo '<table class="checkbox"><tr>';
            if ($length !== 0) {
                for ($i=0;$i<$length;$i++) {
                    if ($i%6===0 & $i!==0) echo '</tr><tr>';
                    $str_checked = $arr[$i]['checked'] == 1 ? 'checked="checked"' : '';
                    echo '<td class="ui-widget-content"><input type="checkbox" '.$str_checked.' value="'.self::htmlConv($arr[$i]['value']).'" id="'.$name.'_'.$i.'" name="'.$name.'[]" /><label for="'.$name.'_'.$i.'">'.self::htmlConv($arr[$i]['label']).'</label></td>';
                }
            }
            echo '</tr></table>';
        } else {
            $arr_val = array();
            for ($i=0;$i<$length;$i++) {
                if ($arr[$i]['checked'] == 1) {
                    array_push($arr_val, self::htmlConv($arr[$i]['label']));
                }
            }
			echo '<p>'.implode(", ", $arr_val).'</p>';
        }
        echo '</span></div>';
	}

	public static function PassWord($name, $value, $label='', $highlight=false, $mandatory=0) {
	    $value = self::htmlConv($value);
		if ($label === '') $label = $name;
        $strReadonly = self::$strReadonly;
        $strHighlight = ($strReadonly !== '' & $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
        $strMandatory = '';
        if ($mandatory > 0) {
            $strMandatory = '<ins title="mandatory field">' . str_repeat('*', $mandatory) . '</ins>';
        }
        echo <<< HTML
        <div class="form-item {$strHighlight}">
            <span class="grid-l"><label for="$name">{$strMandatory}{$label} :</label></span>
            <span class="grid-r">
                <input id="$name" name="$name" type="password" class="ruler input_status text" value="" />
            </span>
        </div>
HTML;
	}

	public static function SubmitButton($class='', $value) {
	    $value = self::htmlConv($value);
        echo <<< HTML
		    <input type="submit" name="$class" value="$value" class="ui-state-default ui-corner-all btn $class" />
HTML;
	}

	public static function ResetButton($class='', $value) {
	    $value = self::htmlConv($value);
        echo <<< HTML
		    <input type="reset" value="$value" class="ui-state-default ui-corner-all btn $class" />
HTML;
	}

	public static function Button($class='', $value, $id='') {
	    $value = self::htmlConv($value);
		$id_string = $id? " id=\"$id\"" : '';
        echo <<<HTML
		    <input type="button" value="$value" class="ui-state-default ui-corner-all btn $class" $id_string />
HTML;
	}


	public static function Duration($label, $name1, $name2, $date1, $date2, $highlight=false, $mandatory=0) {
        $strReadonly = self::$strReadonly;
        $strHighlight = ($strReadonly !== '' & $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
        $strMandatory = '';
        if ($mandatory > 0) {
            $strMandatory = '<ins title="mandatory field">' . str_repeat('*', $mandatory) . '</ins>';
        }
        echo <<< HTML
        <div class="form-item {$strHighlight}">
            <span class="grid-l"><label for="$name1">{$strMandatory}{$label} :</label></span>
            <span class="grid-r">
                <input type="text" name="$name1" value="$date1" class="datepicker" autocomplete="off" $strReadonly />
                &ndash;
                <input type="text" name="$name2" value="$date2" class="datepicker" autocomplete="off" $strReadonly />
            </span>
        </div>
HTML;
	}

	public static function DatePicker($name, $date='',$label, $highlight=false) {
        $strReadonly = self::$strReadonly;
        $strHighlight = ($strReadonly !== '' & $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
        $strClass = ($strReadonly === '') ? 'class="datepicker "' : '';
        echo <<< HTML
        <div class="form-item {$strHighlight}">
            <span class="grid-l"><label for="$name">$label :</label></span>
            <span class="grid-r">
                <input type="text" name="$name" value="$date" autocomplete="off" $strClass $strReadonly />
            </span>
        </div>
HTML;
	}

	public static function TimeHhMmSs(array $name, array $value, $label='', $highlight=false, $mandatory=0) {
        $strReadonly = self::$strReadonly;
        $strHighlight = ($strReadonly !== '' & $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
		$name_hh = $name[0];
		$name_mm = $name[1];
		$name_ss = $name[2];

		$value_hh = $value[0];
		$value_mm = $value[1];
		$value_ss = $value[2];

        if ($mandatory > 0) {
            $strMandatory = '<ins title="mandatory field">' . str_repeat('*', $mandatory) . '</ins>';
        }
		else
		{
			$strMandatory = '';
		}
		echo <<<HTML
        <div class="form-item timeHhMmSs {$strHighlight}">
			<span class="grid-l">
			<label for="$name">{$strMandatory}{$label} :</label>
			</span>
			<span class="grid-r">
			<input id="{$name_hh}" name="{$name_hh}" type="text" value="{$value_hh}" $strReadonly />:
			<input id="{$name_mm}" name="{$name_mm}" type="text" value="{$value_mm}" $strReadonly />:
			<input id="{$name_ss}" name="{$name_ss}" type="text" value="{$value_ss}" $strReadonly />
            </span>
        </div>
HTML;
	}

	public static function DateTimePicker($name, $date=array('', ''), $label, $highlight=false, $mandatory=0) {
        $strReadonly = self::$strReadonly;
        $strHighlight = ($strReadonly !== '' & $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
        $name = $name.'[]';
		$date_new = $date[0];
		$time = $date[1];
        if ($mandatory > 0) {
            $strMandatory = '<ins title="mandatory field">' . str_repeat('*', $mandatory) . '</ins>';
        }
		else
		{
			$strMandatory = '';
		}
        echo <<< HTML
        <div class="form-item {$strHighlight}">
            <span class="grid-l"><label for="$name">{$strMandatory}$label :</label></span>
            <span class="grid-r">
                <input type="text" name="$name" value="$date_new" autocomplete="off" class="datepicker" $strReadonly /> /
                <input type="text" name="$name" value="$time" autocomplete="off" class="time" $strReadonly />
            </span>
        </div>
HTML;
	}
	public static function FileUpload($name, $label='', $thumbnail_url='', $source_url='', $highlight=false, $mandatory=0) {
		$strReadonly = self::$strReadonly;
        $strHighlight = ($strReadonly !== '' & $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
        if ($mandatory > 0) {
            $strMandatory = '<ins title="mandatory field">' . str_repeat('*', $mandatory) . '</ins>';
        } else {
			$strMandatory = '';
		}
        $strInput = '';
        $strImg = '';
        if ($strReadonly == '') {
            $strInput = '<input id="'.$name.'" name="'.$name.'" type="file" />';
        }
        if ($thumbnail_url != '') {
            $strImg = '<a class="preview" href="'.$source_url.'" title="Click for Preview" target="_blank"><img class="thumb" src="'.$thumbnail_url.'" /></a><br />';
        }
        if ($label === '') $label = $name;
        echo <<<HTML
        <div class="form-item form-item-1c {$strHighlight}">
            <span class="grid-l"><label for="$name">{$strMandatory}{$label} :</label></span>
            <span class="grid-r">
                {$strImg}
                {$strInput}
            </span>
        </div>
HTML;
	}

	public static function SingleCheckBox($name, $checked, $label='', $highlight=false) {
	    $label = self::htmlConv($label);
        $strReadonly = self::$strReadonly;
        $strReadonly = ($strReadonly == '') ? '' : 'disabled="disabled"';
        $strHighlight = ($strReadonly !== '' & $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
		if ($label === '') $label = $name;
		$str_checked = $checked ? 'checked="checked"' : '';
        echo <<<HTML
        <div class="form-item {$strHighlight}">
            <span class="grid-l"><label for="$name">{$label} :</label></span>
            <span class="grid-r">
                <input type="checkbox" $str_checked value="true" id="$name" name="$name" $strReadonly/>
            </span>
        </div>
HTML;
		
	}

	public static function RedCallers($name, $arr) {
        $strReadonly = self::$strReadonly;
        $addButton = $strReadonly !== '' ? '' : '<input type="button" value="Add" class="btn ui-state-default ui-corner-all red" />';
		$json_item = array();
        foreach ($arr['folders'] as $folder) {
			$json_item['fname'] = '';
			$json_item['ptype'] = $arr['ptype'];
			$json_item['pid'] = $arr['pid'];
			$json_item['fid'] = $folder['fid'];
			$json_item['ftype'] = $folder['ftype'];
			$json_item['fspec'] = $folder['fspec'];
			$json_item['user_id'] = CommonUtils::get_user();
			$json_encode_item = json_encode($json_item);
            $highlight = isset($folder['highlight']) ? $folder['highlight'] : false;
            $strHighlight = ($strReadonly !== '' & $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
            $str_item_list = '';
            $str_ftype_class = $folder['ftype'] === '1' ? 'video' : 'image';
            if (count($folder['items']) > 0) {
                $str_item_list .= '<ul class="ui-widget-content">';
                foreach($folder['items'] as $item){
                    $str_item_list .= '<li><div>';
                    $str_item_list .= '<span>'.$item['status'].'</span>';
                    $str_item_list .= '<a class="preview '.$str_ftype_class.'" href="'.$item['src'].'" title="Click for Preview" target="_blank"><img src="'.$item['thumb'].'" /></a>';
                    $str_item_list .= '<p title="'.str_replace('<br />'," \n ",$item['title']).'">'.mb_strimwidth($item['title'],0,33,'...','UTF-8').'</p>';
                    if ($item['src'] && $folder['ftype'] == AC::FOLDER_TYPE_VIDEO && $item['flag'] !== false && $folder['fspec']==AC::VIDEO_CATCHUP) {
                        $str_item_list .= '<a class="btn ui-state-default ui-corner-all edit chapter-marking" href=#'.$item['id'].'>Edit Video</a>';
                    }
                    $str_item_list .= '</div></li>';
                }
                $str_item_list .= '</ul>';
            }
            echo <<< HTML
            <div class="form-item form-item-1c red-callers $strHighlight">
                <span class="grid-l">
                    {$folder['fname']} : <br />
                    [folder id:{$folder['fid']}]<br />
                    [folder path:{$folder['path']}]
                </span>
    		    <span class="grid-r">
                    <div class="item-list">{$str_item_list}</div>
    		        {$addButton}<strong>0</strong> item(s) newly selected. / <strong>{$folder['total']}</strong> item(s) totally selected.
					<input type="hidden" class="fvars" value='{$json_encode_item}'>
               	</span>
            </div>
HTML;
        }
	}
	
	public static function RedCallers2($name, $arr) {
        $strReadonly = self::$strReadonly;
        $addButton = $strReadonly !== '' ? '' : '<br /><input type="button" value="Add" class="btn ui-state-default ui-corner-all red" />';
		$json_item = array();
        foreach ($arr['folders'] as $folder) {
			$json_item['fname'] = '';
			$json_item['ptype'] = $arr['ptype'];
			$json_item['pid'] = $arr['pid'];
			$json_item['fid'] = $folder['fid'];
			$json_item['ftype'] = $folder['ftype'];
			$json_item['fspec'] = $folder['fspec'];
			$json_item['user_id'] = CommonUtils::get_user();
			$json_item['premium'] = $folder['premium']; 
			$json_encode_item = json_encode($json_item);
            $highlight = isset($folder['highlight']) ? $folder['highlight'] : false;
            $strHighlight = ($strReadonly !== '' & $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
            $str_ftype_class = $folder['ftype'] === '1' ? 'video' : 'image';
            echo <<< HTML
            <div class="red-callers $strHighlight">
                <fieldset class="ui-widget-content">
                    <legend class="ui-widget-header">{$folder['fname']} [folder id:{$folder['fid']}, folder path:{$folder['path']}]</legend>
                    <div class="item-list cms-jqgrid"><table class="scroll"></table><div class="scroll"></div></div>
    		        {$addButton}<strong>0</strong> item(s) newly selected. / <strong>{$folder['total']}</strong> item(s) totally selected.
					<input readonly="true" autocomplete="off" type="hidden" class="fvars" value='{$json_encode_item}'>
				</fieldset><br />
            </div>
HTML;
        }
    }

	public static function MISGlobalNameInput($arr_cast_type, $arr_name_data, $simple_mode=0, $key="", $highlight=array()) {
        $strReadonly = self::$strReadonly;
		$arr_name_type = array(
            '1'=>'Name',
            '11'=>'Other Name',
            '2'=>'Cast Name',
            '12'=>'Cast Nickname'
        );
        switch ($simple_mode) {
            case 0:
                $class_simple_mode = '';
            break;
            case 1:
                $class_simple_mode = 'simple-mode1';
            break;
            case 2:
                $class_simple_mode = 'simple-mode2';
            break;
        }
        foreach ($arr_cast_type as $role_id=>$cast) {
            $rows = '';
            //main cast(role_id = 1) can be sortable
            $colSort =  $role_id === 1 ? '<td><a href="#"><span class="ui-icon ui-icon-arrowthick-1-n"></span></a><a href="#" class="btn down ui-state-default ui-corner-all"><span class="ui-icon ui-icon-arrowthick-1-s"></span></a></td>' : '';
            $template = <<<TR
                <tr>
                    <td class="ui-widget-content">
                        <input type="checkbox" class="alphabet" checked="checked" /><input class="alphabet_data" type="hidden" value="1" name="alphabet[$role_id][]" /> 中文
                    </td>
                    <td>
                        <input type="hidden" class="role-id" value="{$role_id}" />
                        <select class="name-type" name="name_type[$role_id][]">
                            <option value="1" selected="selected">Name</option>
                            <option value="11">Other Name</option>
                            <option value="2">Cast Name</option>
                            <option value="12">Cast Nickname</option>
                        </select>
                    </td>
                    <td>
                        <span class="last">
                            <span><ins class="en">Last Name</ins><ins class="cn">姓</ins></span>
                            <input class="cast-name" name="name_last[$role_id][]" type="text" value="" />
                        </span>
                        <span class="first">
                            <span><ins class="en">First Name</ins><ins class="cn">名</ins></span>
                            <input class="cast-name" name="name_first[$role_id][]" type="text" value="" />
                        </span>
                    </td>
                    <td class="ui-widget-content">
                        <input type="hidden" value="" name="cast_id[$role_id][]" />
                        <input type="button" value="Detail" class="btn detail ui-state-default ui-corner-all" />
                        <a href="#" class="btn del ui-state-default ui-corner-all"><span class="ui-icon ui-icon-minus"></span></a>
                    </td>
                    $colSort
                </tr>
TR;
            $plus_readonly = ($strReadonly == '') ? '<a href="#" class="btn add ui-state-default ui-corner-all"><span class="ui-icon ui-icon-plus"></span></a>' : '';
            $template = htmlspecialchars($template);
            if (isset($arr_name_data[$role_id])) {
                $i = 0;    //for sorting
                $j = count($arr_name_data[$role_id]);
                foreach ($arr_name_data[$role_id] as $cast_info) {
                    $str_name_type = '<select class="name-type" name="name_type['.$role_id.']['.$i.']">';
                    foreach ($arr_name_type as $key_type=>$value) {
                        $str_selected = ($key_type == $cast_info['name_type']) ? 'selected="selected"' : '';
                        $str_name_type .= '<option value="'.$key_type.'" '.$str_selected.' >'.$value.'</option>';
                    }
                    $last_name = self::htmlConv($cast_info['last_name']);
                    $first_name = self::htmlConv($cast_info['first_name']);
                    $checked = ($cast_info['alphabet'] == 1) ? "checked=\"checked\"" : "";
                    $alphabet = $cast_info['alphabet'];
                    $cast_id = $cast_info['cast_id'];
                    $class_single = ($cast_info['name_type'] > 10)? "single" : "";
                    $class_en = ($cast_info['alphabet'] == 1) ? "" : " en ";
                    $str_name_type .= '</select>';
                    $rowClass = '';
                    if ($i === 0 && $j === 1) {
                        $rowClass = 'class="fst lst"';
                    } elseif ($i === 0 && $i < $j) {
                        $rowClass = 'class="fst"';
                    } elseif ($i === $j - 1) {
                        $rowClass = 'class="lst"';
                    }

                   
                        $name_type_key = $cast_info['name_type'];
                        $name_type_readonly = $arr_name_type[$name_type_key];
						$last_name_readonly  = ($alphabet == 1) ? $last_name : $first_name;
						$first_name_readonly = ($alphabet == 1) ? $first_name : $last_name;
                        $cast_id = $cast_info['cast_id'];
                        $detail_readonly = ($cast_id == '') ? '' : '<input type="button" value="Detail" class="btn detail ui-state-default ui-corner-all" />';
                    $tr = <<<TR
                            <tr>
                                <td class="">
                                    <span>({$name_type_readonly})</span>
                                </td>
                                <td class="{$class_en} {$class_single}">
                                    <span class="last">{$last_name_readonly}</span>
                                    <span class="first">{$first_name_readonly}</span>
                                </td>
                                <td class="">
                                    <input type="hidden" value="{$alphabet}" name="alphabet[$role_id][]" /> 
                                </td>
                                <td class="">
                                    <input type="hidden" value="{$cast_id}" name="cast_id[$role_id][]" />
                                    {$detail_readonly}
                                </td>
                            </tr>
TR;

                    $rows.= $tr;
                    $i++;
                }
            }
            $strHighlight = ($strReadonly !== '' && isset($highlight[$role_id]) && $highlight[$role_id]) ? self::HIGHLIGHT_CSSCLASS : '';
            echo <<<HTML
            <div class="form-item">
                <span class="grid-l"><label>{$cast}</label>:</span>
                <span class="grid-r global-name">
                    <table class="{$class_simple_mode}"><tbody>
                    {$rows}
                    </tbody></table>
                    {$plus_readonly}
                    <input type="hidden" class="template" value="{$template}" />
                </span>
            </div>
HTML;
        }
    }

	public static function GlobalNameInput($arr_cast_type, $arr_name_data, $simple_mode=0, $key="", $highlight=array()) {
        $strReadonly = self::$strReadonly;
		$arr_name_type = array(
            '1'=>'Name',
            '11'=>'Other Name',
            '2'=>'Cast Name',
            '12'=>'Cast Nickname'
        );
        switch ($simple_mode) {
            case 0:
                $class_simple_mode = '';
            break;
            case 1:
                $class_simple_mode = 'simple-mode1';
            break;
            case 2:
                $class_simple_mode = 'simple-mode2';
            break;
        }
        foreach ($arr_cast_type as $role_id=>$cast) {
            $rows = '';
            //main cast(role_id = 1) can be sortable
            $colSort =  $role_id === 1 ? '<td class="ui-widget-content"><a href="#" class="btn up ui-state-default ui-corner-all"><span class="ui-icon ui-icon-arrowthick-1-n"></span></a><a href="#" class="btn down ui-state-default ui-corner-all"><span class="ui-icon ui-icon-arrowthick-1-s"></span></a></td>' : '';
            $template = <<<TR
                <tr>
                    <td class="ui-widget-content">
                        <input type="checkbox" class="alphabet" checked="checked" /><input class="alphabet_data" type="hidden" value="1" name="alphabet[$role_id][]" /> 中文
                    </td>
                    <td class="ui-widget-content">
                        <input type="hidden" class="role-id" value="{$role_id}" />
                        <select class="name-type" name="name_type[$role_id][]">
                            <option value="1" selected="selected">Name</option>
                            <option value="11">Other Name</option>
                            <option value="2">Cast Name</option>
                            <option value="12">Cast Nickname</option>
                        </select>
                    </td>
                    <td class="ui-widget-content">
                        <span class="last">
                            <span><ins class="en">Last Name</ins><ins class="cn">姓</ins></span>
                            <input class="cast-name" name="name_last[$role_id][]" type="text" value="" />
                        </span>
                        <span class="first">
                            <span><ins class="en">First Name</ins><ins class="cn">名</ins></span>
                            <input class="cast-name" name="name_first[$role_id][]" type="text" value="" />
                        </span>
                    </td>
                    <td class="ui-widget-content">
                        <input type="hidden" value="" name="cast_id[$role_id][]" />
                        <input type="button" value="Detail" class="btn detail ui-state-default ui-corner-all" />
                        <a href="#" class="btn del ui-state-default ui-corner-all"><span class="ui-icon ui-icon-minus"></span></a>
                    </td>
                    $colSort
                </tr>
TR;
            $plus_readonly = ($strReadonly == '') ? '<a href="#" class="btn add ui-state-default ui-corner-all"><span class="ui-icon ui-icon-plus"></span></a>' : '';
            $template = htmlspecialchars($template);
            if (isset($arr_name_data[$role_id])) {
                $i = 0;    //for sorting
                $j = count($arr_name_data[$role_id]);
                foreach ($arr_name_data[$role_id] as $cast_info) {
                    $str_name_type = '<select class="name-type" name="name_type['.$role_id.']['.$i.']">';
                    foreach ($arr_name_type as $key_type=>$value) {
                        $str_selected = ($key_type == $cast_info['name_type']) ? 'selected="selected"' : '';
                        $str_name_type .= '<option value="'.$key_type.'" '.$str_selected.' >'.$value.'</option>';
                    }
                    $last_name = self::htmlConv($cast_info['last_name']);
                    $first_name = self::htmlConv($cast_info['first_name']);
                    $checked = ($cast_info['alphabet'] == 1) ? "checked=\"checked\"" : "";
                    $alphabet = $cast_info['alphabet'];
                    $cast_id = $cast_info['cast_id'];
                    $class_single = ($cast_info['name_type'] > 10)? "single" : "";
                    $class_en = ($cast_info['alphabet'] == 1) ? "" : " en ";
                    $str_name_type .= '</select>';
                    $rowClass = '';
                    if ($i === 0 && $j === 1) {
                        $rowClass = 'class="fst lst"';
                    } elseif ($i === 0 && $i < $j) {
                        $rowClass = 'class="fst"';
                    } elseif ($i === $j - 1) {
                        $rowClass = 'class="lst"';
                    }
                    if ($strReadonly === '') {
                    $tr = <<<TR
                            <tr $rowClass>
                                <td class="ui-widget-content">
                                    <input type="checkbox" class="alphabet" {$checked} /><input class="alphabet_data" type="hidden" value="{$alphabet}" name="alphabet[$role_id][$i]" /> 中文
                                </td>
                                <td class="ui-widget-content">
                                    <input type="hidden" class="role-id" value="{$role_id}" />
                                    {$str_name_type}
                                </td>
                                <td class="ui-widget-content {$class_en} {$class_single}">
                                    <span class="last">
                                        <span><ins class="en">Last Name</ins><ins class="cn">姓</ins></span>
                                        <input class="cast-name" name="name_last[$role_id][$i]" type="text" value="{$last_name}" />
                                    </span>
                                    <span class="first">
                                        <span><ins class="en">First Name</ins><ins class="cn">名</ins></span>
                                        <input class="cast-name" name="name_first[$role_id][$i]" type="text" value="{$first_name}" />
                                    </span>
                                </td>
                                <td class="ui-widget-content">
                                    <input type="hidden" value="{$cast_id}" name="cast_id[$role_id][$i]" />
                                    <input type="button" value="Detail" class="btn detail ui-state-default ui-corner-all" />
                                    <a href="#" class="btn del ui-state-default ui-corner-all"><span class="ui-icon ui-icon-minus"></span></a>
                                </td>
                                $colSort
                            </tr>
TR;
                    } else {
                        $name_type_key = $cast_info['name_type'];
                        $name_type_readonly = $arr_name_type[$name_type_key];
						$last_name_readonly  = ($alphabet == 1) ? $last_name : $first_name;
						$first_name_readonly = ($alphabet == 1) ? $first_name : $last_name;
                        $cast_id = $cast_info['cast_id'];
                        $detail_readonly = ($cast_id == '') ? '' : '<input type="button" value="Detail" class="btn detail ui-state-default ui-corner-all" />';
                    $tr = <<<TR
                            <tr>
                                <td class="">
                                    <span>({$name_type_readonly})</span>
                                </td>
                                <td class="{$class_en} {$class_single}">
                                    <span class="last">{$last_name_readonly}</span>
                                    <span class="first">{$first_name_readonly}</span>
                                </td>
                                <td class="">
                                    <input type="hidden" value="{$alphabet}" name="alphabet[$role_id][]" /> 
                                </td>
                                <td class="">
                                    <input type="hidden" value="{$cast_id}" name="cast_id[$role_id][]" />
                                    {$detail_readonly}
                                </td>
                            </tr>
TR;
                    }
                    $rows.= $tr;
                    $i++;
                }
            }
            $strHighlight = ($strReadonly !== '' && isset($highlight[$role_id]) && $highlight[$role_id]) ? self::HIGHLIGHT_CSSCLASS : '';
            echo <<<HTML
            <div class="form-item form-item-1c {$strHighlight}">
                <span class="grid-l"><label>{$cast}</label>:</span>
                <span class="grid-r global-name">
                    <table class="{$class_simple_mode}"><tbody>
                    {$rows}
                    </tbody></table>
                    {$plus_readonly}
                    <input type="hidden" class="template" value="{$template}" />
                </span>
            </div>
HTML;
        }
    }


	public static function EditableList($data, $allow, $label,$key='', $type='', $ajax_api='', $highlight=false, $mandatory=0, $autocomplete=false)
	{
		$strReadonly = self::$strReadonly;
        $strHighlight = ($strReadonly !== '' & $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
		$li_str = "";
		$str = "";
        $add_btn_str = '';
		$key = ($key == '') ? '' : "{$key}";
        if (isset($allow['id'])) {
            $tag_type_id = $allow['id'];
        }
        if ($mandatory > 0) {
            $strMandatory = '<ins title="mandatory field">' . str_repeat('*', $mandatory) . '</ins>';
        } else {
			$strMandatory = '';
		}
		foreach($data as $index=>$arr) {
			$sname = self::htmlConv($arr['system_label']);
			$id = $arr['id'];
            $tag_type_field = '';
			if(empty($arr['is_new'])) $name_key = $key.'['.$index.']';
			else $name_key = $key.'['.$index.'][new]';

            if (isset($allow['id'])) {
                $tag_type_field = '<input type="hidden" name="tag['.$tag_type_id.']'.$name_key.'" value="'.$id.'">';
            } else {
				$tag_type_field = '<input type="hidden" name="'.$name_key.'" value="'.$id.'">';
			}			

            $cast_tag_id = '';
            if(preg_match ("/cast/", $type)){
                $cast_tag_id = <<<HTML
                <span class='tagId'>{$id}</span>: 
HTML;
            }

			if ($strReadonly == '') {
			    $sort_btns = '';
    			if(preg_match ("/tvb\.com_cat|seo|tag/", $type)){
                    $sort_btns = <<<BTNS
                    <a class="btn-up btn" href="#"><span class="ui-icon ui-icon-arrowthick-1-n"></span></a>
                    <a class="btn-dn btn" href="#"><span class="ui-icon ui-icon-arrowthick-1-s"></span></a>
BTNS;
                }                

				$li =<<<ITEM
	<li>{$cast_tag_id}<span class='tag'>{$sname}</span>{$tag_type_field}{$sort_btns}<a class="btn-del" href="#">del</a></li>
ITEM;
				$li_str.=$li;
			} else {
				$li_str .= '<li>'.$cast_tag_id.$sname."</li>";
			}
		}

        if ($autocomplete && $strReadonly=='') {
            $str = <<<EOD
                <input type="text" class="text editable" autocomplete="off" value="" /><a class="btn add ui-state-default ui-corner-all" href="{$ajax_api}">Add</a>
                <input type="hidden" class="id" value="" />
EOD;
        } else {
    		if (0 == $allow['restrict'] && $strReadonly=='') {
    			$str = <<<EOD
                    <input type="text" class="text editable" name="" value="" /><a class="btn add ui-state-default ui-corner-all" href="">Add</a>
EOD;
    		}
    			$add_btn_str = <<<BTN
                    <a class="btn ui-state-default ui-corner-all addpop" href="{$ajax_api}">Select</a>
BTN;
            $add_btn_str = ($strReadonly) ? "" : $add_btn_str;
        }



		echo <<<TAG
                <div class="form-item {$strHighlight}">
                    <span class="grid-l"><label>{$strMandatory}{$label}</label> :</span>
                    <span class="grid-r editable-list">
						<ul class="ui-widget-content">
						{$li_str}
						</ul>
						{$str}
                        <input class="type" type="hidden" value="{$type}">
						{$add_btn_str}
                    </span>
                </div>
TAG;
	}

	//public static function EditableList2($data, $allow, $label,$key='', $type='', $ajax_api='', $highlight=false, $mandatory=0, $autocomplete=false)
	public static function EditableList2($name='', $value='', $label='', $options=array()) {
		$strReadonly = self::$strReadonly;
        $strHighlight = ($strReadonly !== '' & $highlight) ? self::HIGHLIGHT_CSSCLASS : '';
		$li_str = "";
		$str = "";
        $add_btn_str = '';
		$key = ($key == '') ? '' : "{$key}";
        if (isset($allow['id'])) {
            $tag_type_id = $allow['id'];
        }
        if ($mandatory > 0) {
            $strMandatory = '<ins title="mandatory field">' . str_repeat('*', $mandatory) . '</ins>';
        } else {
			$strMandatory = '';
		}
		foreach($data as $arr) {
			$sname = self::htmlConv($arr['system_label']);
			$id = $arr['id'];
            $tag_type_field = '';
            if (isset($allow['id'])) {
                $tag_type_field = '<input type="hidden" name="tag['.$tag_type_id.']'.$key.'[]" value="'.$id.'">';
            } else {
				$tag_type_field = '<input type="hidden" name="'.$key.'[]" value="'.$id.'">';
			}			
            
			if ($strReadonly == '') {
			    $sort_btns = '';
    			if(preg_match ("/tvb\.com_cat|seo|tag/", $type)){
                    $sort_btns = <<<BTNS
                    <a class="btn-up btn" href="#"><span class="ui-icon ui-icon-arrowthick-1-n"></span></a>
                    <a class="btn-dn btn" href="#"><span class="ui-icon ui-icon-arrowthick-1-s"></span></a>
BTNS;
                }
				$li =<<<ITEM
	<li><span class='tag'>{$sname}</span>{$tag_type_field}{$sort_btns}<a class="btn-del" href="#">del</a></li>
ITEM;
				$li_str.=$li;
			} else {
				$li_str .= '<li>'.$sname."</li>";
			}
		}

        if ($autocomplete && $strReadonly=='') {
            $str = <<<EOD
                <input type="text" class="text editable" autocomplete="off" value="" /><a class="btn add ui-state-default ui-corner-all" href="{$ajax_api}">Add</a>
                <input type="hidden" class="id" value="" />
EOD;
        } else {
    		if (0 == $allow['restrict'] && $strReadonly=='') {
    			$str = <<<EOD
                    <input type="text" class="text editable" name="" value="" /><a class="btn add ui-state-default ui-corner-all" href="">Add</a>
EOD;
    		}
    			$add_btn_str = <<<BTN
                    <a class="btn ui-state-default ui-corner-all addpop" href="{$ajax_api}">Select</a>
BTN;
            $add_btn_str = ($strReadonly) ? "" : $add_btn_str;
        }



		echo <<<TAG
                <div class="form-item {$strHighlight}">
                    <span class="grid-l"><label>{$strMandatory}{$label}</label> :</span>
                    <span class="grid-r editable-list">
						<ul class="ui-widget-content">
						{$li_str}
						</ul>
						{$str}
                        <input class="type" type="hidden" value="{$type}">
						{$add_btn_str}
                    </span>
                </div>
TAG;
	}

	public static function ErrorMessages($errors)
	{
		global $errMsg;
		if (count($errors) > 0)
		{
			$li_str = '';
			foreach ($errors as $key=>$msg)
			{
				$error_num = $msg[0]->content[0];
				$li_str .= "<li><strong>".$msg[0]->content[1]."</strong> -> ".AC::PRODUCT_NAME.$error_num.AC::ERROR_CODE_SUFFIX.":".$errMsg[$error_num]."</li>";
			}
		echo <<<TAG
		<div class="com-err ui-state-error">
		<h3>Error Messages</h3>
		<ol>
		{$li_str}
		</ol>
		</div>
TAG;
		}
	}

    public static function DisplayPublishLog($object)
    {
        if (isset($object->non_premium)) {
            $publish_log = $object->non_premium;
            $publish_log->published_at   =   str_replace('<br />', ' ', $publish_log->published_at);
            echo <<<PublishLog_non_premium
        <fieldset class="ui-widget-content">
            <legend class="ui-widget-header">Record Status and Publish Log</legend>
PublishLog_non_premium;
            self::ProtectedField(AC::$op_status[$publish_log->status], 'Status', true);
            self::ProtectedField($publish_log->published_by, 'Performed By');
            self::ProtectedField($publish_log->published_at, 'Performed At');
            echo <<<PublishLog_non_premium
        </fieldset>
PublishLog_non_premium;
        }

        if (isset($object->premium)) {
            $publish_log = $object->premium;
            $publish_log->published_at   =   str_replace('<br />', ' ', $publish_log->published_at);
            echo <<<PublishLog_premium
        <fieldset class="ui-widget-content">
            <legend class="ui-widget-header">Record Status and Publish Log (Premium)</legend>
PublishLog_premium;
            self::ProtectedField(AC::$op_status[$publish_log->status], 'Status', true);
            self::ProtectedField($publish_log->published_by, 'Performed By');
            self::ProtectedField($publish_log->published_at, 'Performed At');
            echo <<<PublishLog_premium
        </fieldset>
PublishLog_premium;
        }
    }

    public static function Separator($css_class='') {
        $str_class = '';
        if (!$css_class == '') {
            $str_class = ' '.$css_class;
        }
        echo <<<HTML
        <div class="separator{$str_class}"><hr class="ui-widget-content" /></div>
HTML;
    }

/*
            $table_data = array(
                array(    //row data
                    'field'=>'id',
                    'new_value'=>'a new value here..',
                    'old_value'=>'a old value here...',
                    'modified_at'=>'2009-12-30'
                ),
                array(
                    'field'=>'id',
                    'new_value'=>'a new value here..',
                    'old_value'=>'a old value here...',
                    'modified_at'=>'2009-12-30'
                )
            );
            $colOptions = array(    //only render 2 columns
                array('col_name'=>'Field', 'field'=>'field', 'ui_class'=>''),
                array('col_name'=>'New Value', 'field'=>'new_value', 'ui_class'=>'')
            );
*/
    public static function Table($table_data, $colOptions) {
        $strBuffer = array();
        foreach ($colOptions as $col) {
            $strBuffer[] = '<th class="ui-widget-header '.$col['ui_class'].'">'.$col['col_name'].'</th>';
        }
        $hd_cols = implode('', $strBuffer);

        $strBuffer = array();
        foreach($table_data as $row) {
            $strBuffer[] = '<tr>';
            foreach($colOptions as $col) {
                $strBuffer[] = '<td class="ui-widget-content">'.$row[$col['field']].'</td>';
            }
            $strBuffer[] = '</tr>';
        }
        $bd_rows = implode('', $strBuffer);
        echo <<<HTML
        <table class="grid">
            <thead>
            <tr class="ui-widget-header">
                {$hd_cols}
            </tr>
            </thead>
            <tbody>
                {$bd_rows}
            </tbody>
        </table>
HTML;
    }


    public static function CountryList($name, $label='', $value=array(), $options=array()) {
/**
 * $name = 'countrys';
 * $label = 'Region / Country';
 * $value = array(
 *      'Africa'=>array(
 *          'Africa'=>array('AO'=>'Angola','CM'=>'Cameroon','EG'=>'Egypt')
 *      ),
 *      'Asia'=>array(
 *          'Asia'=>array('CN'=>'China','HK'=>'Hong Kong')
 *      ),
 *      'Oceania'=>'ALL'
 * );
 * $options = array(
 *      'stat'=>array(
 *          'Africa'=>'Africa',
 *          'Asia'=>'Asia',
 *          'Europe'=>'Europe',
 *          'North America'=>'North America',
 *          'South America'=>'South America',
 *          'Oceania'=>'Oceania',
 *          'Others'=>'Others'
 *      ),
 *      'service'=>'services/get_country.php',
 *      'selectIndex'=>'2',
 *      'mandatory'=>'1'
 * )
 */
        $value = empty($value)? array() : $value;
        $options = empty($options)? array() : $options;

        $stat = empty($options['stat']) ? array() : $options['stat'];
        $service = empty($options['service']) ? '' : $options['service'];
        $selectIndex = empty($options['selectIndex']) ? '1' : $options['selectIndex'];
        $mandatory = empty($options['mandatory']) ? 0 : $options['mandatory'];

        $strMandatory = '';
        if ($mandatory > 0) {
            $strMandatory = '<ins title="mandatory field">' . str_repeat('*', $mandatory) . '</ins>';
        }
        $label = ($label=='') ? "<label>&nbsp;</label>" : "<label>{$strMandatory}{$label}</label> :";
        $inline_css = ($label=='') ? "" : "style='padding-top:0;'";

        $view_class = (self::$strReadonly=='')?'':'view';

        $tabs = '';
        if(count($stat)){
            foreach($stat as $k=>$v){
                $tabs .= '<li><a href="'.$service.'?region='.$k.'">'.$v.'</a></li>';
            }
        }

        $value = json_encode($value);

        echo <<<HTML
<div class="cms-form-item cms-countrylist cms-countrylist-item cms-form-item-1c" {$inline_css}>
    <span class="grid-l">
        {$label}
    </span>
    <span class="grid-r {$view_class}">
        <input class="vcountry" type="hidden" name="{$name}" value='{$value}' />
		<div class="list ui-helper-clearfix"></div>
		<input type="button" value="Select Region/Country" class="ui-state-default ui-corner-all cms-btn select-btn" />
		<input type="button" value="Reset" class="ui-state-default ui-corner-all cms-btn reset-btn" />
    </span>
	
    <div class="cms-countrylist cms-countrylist-pop">
    	<ul class="tabs" selectIndex="{$selectIndex}">
		    {$tabs}
    	</ul>
	    <div class="subtabs">
	    	<ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix">
		    	<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#">A-G</a></li>
		    	<li class="ui-state-default ui-corner-top"><a href="#">H-N</a></li>
		    	<li class="ui-state-default ui-corner-top"><a href="#">O-Z</a></li>
	    	</ul>
    	</div>
    </div>
</div>

HTML;
    }

}

?>
